package com.tabnet.servlet.client;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tabnet.beans.commande.Commande;
import com.tabnet.beans.personnes.Client;
import com.tabnet.dao.DAOCommande;
import com.tabnet.dao.DAOException;
import com.tabnet.dao.DAOFactory;
import com.tabnet.form.client.ValiderCommandeForm;

public class ValiderCommande extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	public static final String ATT_FORM        		= "form";
    public static final String SESSION_COMMANDE     = "commande";
    public static final String SESSION_USER 		= "sessionClient";

    public static final String VUE_SUCCES      		= "/adminClient/accueil.jsp";
    public static final String VUE        			= "/index.jsp";
    
    private DAOCommande _DaoCommande;
    
    public void init() throws ServletException {
        /* Récupération d'une instance de notre DAO Utilisateur */
    	try {
			this._DaoCommande = DAOFactory.getInstance().getCommandeDAO();
		}
    	catch (DAOException e) {
			e.printStackTrace();
		}
    }
    
    public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        
        /* Récupération du client dans la session */
        HttpSession session = request.getSession();

    	Client oClient = (Client) session.getAttribute(SESSION_USER);
    	Commande oCommande = (Commande) session.getAttribute(SESSION_COMMANDE);
    	
    	if(oClient == null)
            this.getServletContext().getRequestDispatcher( VUE ).forward( request, response );

    	/* Préparation de l'objet formulaire */
    	ValiderCommandeForm form = new ValiderCommandeForm(this._DaoCommande);
    	form.updateCommande(request, oCommande);
    	
    	 /* Si aucune erreur */
        if ( form.getErreurs().isEmpty() ) {
            session.setAttribute( SESSION_COMMANDE, null );
            session.setAttribute( SESSION_USER, oClient );
            response.sendRedirect( request.getContextPath() + VUE_SUCCES );
        }
        else {
            session.setAttribute( SESSION_COMMANDE, null );
            session.setAttribute( SESSION_USER, null );
            this.getServletContext().getRequestDispatcher( VUE ).forward( request, response );
        }
    }

    public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
    	this.doGet(request, response); 	
    }

}
